<template>
  <div class="wrapper">
    <!-- 薪酬变化趋势 -->
    <el-row class="search-container">
      <el-form ref="form" label-width="auto">
        <el-form-item label="统计时间：">
          <el-date-picker
            v-model="selectBetweenTime"
            size="small"
            type="monthrange"
            :clearable="false"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            :picker-options="pickerOptions"
            @change="handleDateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="区域名称：">
          <multipleRegoinSearch
            ref="regionRef"
            :limitNum="1"
            @onRegionChange="onRegionChange"
          />
        </el-form-item>
      </el-form>
    </el-row>
    <div class="chartMain">
      <template v-if="chartDataIsNotEmpty">
        <div class="h100" ref="line_echartDom"></div>
        <div class="regionLineDesc">
          <div
            class="regionLineDescItem"
            v-for="(item, index) in chartData.averageSalaryList"
            :key="index"
          >
            <div class="descTitle">{{ item.name }}约</div>
            <div class="descNum">
              <span class="rmb">￥</span>{{ item.value }}/<span class="rmb"
                >月</span
              >
            </div>
          </div>
        </div>
      </template>
      <el-empty class="empty" description="暂无数据" v-else>
        <el-button type="primary" size="mini" @click="handleKnowClick()">
          想要了解
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script>
import { chartRegionSalary, reportLackDataPosition } from "@/api/salary";
import multipleRegoinSearch from "@/views/position/components/multipleRegoinSearch.vue";
export default {
  name: "regionLineChartNew",
  components: {
    multipleRegoinSearch,
  },
  data() {
    return {
      resData: [],
      chartData: {},
      selectBetweenTime: [],
      firstDayofLastMonth: "",
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      pickerMinDate: "",
      pickerOptions: {
        disabledDate: (time) => {
          const nowTime = time.getTime();
          if (nowTime < 1672502400000 || nowTime > this.firstDayofLastMonth) {
            return true;
          }
          if (this.pickerMinDate) {
            const monthsDiff =
              Math.abs(nowTime - this.pickerMinDate) /
              (1000 * 60 * 60 * 24 * 30);
            // 如果相差的月份大于6个月，则禁用该日期
            return monthsDiff > 7 || nowTime < 1672502400000;
          }
        },
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
      },
      average: "",
      selectedRegionList: [],
      regionLineDescAvg: "",
      isSetDeaultTime: false,
      isSetDeaultRegion: true,
      // averageSalaryList:[],// 平均薪酬数组
    };
  },
  created() {
    // 创建一个表示当前日期的 Date 对象
    var currentDate = new Date();

    // 将当前日期设置为本月的第一天
    currentDate.setDate(1);

    // 将当前日期减去一天，得到上个月最后一天
    currentDate.setDate(0);

    // 设置时间为零点
    currentDate.setHours(0, 0, 0, 0);

    // 获取时间戳
    var timestamp = currentDate.getTime();

    this.firstDayofLastMonth = timestamp;
  },
  mounted() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let newYear = 0;
    let newMonth = 0;
    let newDateArr = [];
    for (let i = 0; i < 7; i++) {
      //这里是获取前六个月,所以循环6次,根据需要修改
      if (month - i < 1) {
        //这里的判断是如果当前月份往前推到了去年  需要做的处理
        newYear = year - 1;
        newMonth =
          month - i + 12 >= 10 ? month - i + 12 : "0" + (month - i + 12);
        newDateArr.push(newYear + "-" + newMonth + "-" + "01"); //这里拼接格式化,在时间中间加了个-,根据实际需求来
      } else {
        newMonth = month - i >= 10 ? month - i : "0" + (month - i); //这里是对月份小于10做加前面加0处理
        newDateArr.push(year + "-" + newMonth + "-" + "01");
      }
    }
    //这里就最后得到当前年月前六个月组成的时间数组,根据需要赋值使用即可
    const end = newDateArr[1];
    const start = newDateArr[6];
    // this.isSetDeaultTime = true;
    this.selectBetweenTime = [start, end];
    // console.log(
    //   "this.selectBetweenTime---------->",
    //   this.selectBetweenTime,
    //   newDateArr
    // );

    this.fetchData();
  },
  methods: {
    fetchData() {
      // //console.log("this.selectedRegionList", this.selectedRegionList);

      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
      };
      // params.beginTime = "2023-1-1";
      // params.endTime = "2023-5-1";
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.beginTime = this.selectBetweenTime[0];
        params.endTime = this.selectBetweenTime[1];
        // params.beginTime = "2023-1-1";
        // params.endTime = "2023-5-1";
      }
      params.regionIds = this.selectedRegionList.join("_");
      console.log("----薪酬变化趋势-----params", params);
      chartRegionSalary(params)
        .then((response) => {
          if (response.code == 200) {
            console.log(
              "----薪酬变化趋势-----chartRegionSalary",
              response.data
            );
            this.regionLineDescAvg = response.data.average;
            this.chartData = this.handleData(response.data.list);
            console.log("this.chartData", this.chartData);
            this.chartDataIsNotEmpty =
              response.data.list && response.data.list.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
        });
    },
    handleData(data) {
      let dataArr = {
        city: [],
        time: [],
        name: [],
        averageSalaryList: [],
      };

      if (data[data.length - 1]) {
        data[data.length - 1].salarys.forEach((item) => {
          dataArr.time.push(`${item.month}${item.year}`);
        });
      }

      dataArr.city = data.map((item) => {
        if (item) {
          dataArr.name.push(item.salaryRegionName);
          const maxSalary = [];
          const minSalary = [];
          const averageSalary = [];
          const middleSalary = [];

          item.salarys.forEach((item) => {
            // salaryNum是平均薪资
            // fiftyPercentile 中位数
            // ninetyFivePercentile 最高
            // tenPercentile 最低
            maxSalary.push(item.ninetyFivePercentile); // 最高薪资
            minSalary.push(item.tenPercentile); // 最低薪资
            averageSalary.push(item.salaryNum); // 平均薪资
            middleSalary.push(item.fiftyPercentile); // 中位数薪资
          });

          // 计算各个数组的平均值
          const calculateAverage = (arr) => {
            if (arr.length === 0) return 0;
            const sum = arr.reduce((acc, val) => acc + val, 0);
            return Number((sum / arr.length).toFixed(1));
          };

          // 将计算结果添加到 averageSalaryList
          dataArr.averageSalaryList = [
            {
              name: "平均平均薪资",
              value: calculateAverage(averageSalary),
            },
            {
              name: "平均最高薪资",
              value: calculateAverage(maxSalary),
            },
            {
              name: "平均中位数薪资",
              value: calculateAverage(middleSalary),
            },
            {
              name: "平均最低薪资",
              value: calculateAverage(minSalary),
            },
          ];

          return {
            name: item.salaryRegionName,
            maxSalary,
            minSalary,
            averageSalary,
            middleSalary,
          };
        }
      });

      return dataArr;
    },
    init() {
      if (!this.$refs["line_echartDom"]) {
        console.log(
          "------------------------this.$refs['line_echartDom'] is null"
        );
        return;
      }

      this.myChart = this.$echarts.init(this.$refs["line_echartDom"]);
      let city = this.chartData.city,
        name = this.chartData.name,
        time = this.chartData.time;
      // let option = {
      //   color: [
      //     "#F359AE",
      //     "#34CA6F",
      //     "#066BFF",
      //     "#75E0FF",
      //     "#FFA506",
      //     "#3ba272",
      //     "#fc8452",
      //     "#9a60b4",
      //     "#ea7ccc",
      //   ],
      // xAxis: {
      //   type: "category",
      //   data: time,
      //   name: "(月份)",
      //   // boundaryGap: false,
      //   axisLabel: {
      //     formatter(val) {
      //       // 当字符串长度超过2时
      //       if (val.length > 2) {
      //         // 把字符串分割成字符串数组
      //         const array = val.split("");
      //         const index = array.indexOf("月");
      //         //在下标2处删除0个，加上回车
      //         array.splice(index + 1, 0, "\n\n");
      //         return array.join("");
      //       } else {
      //         return val;
      //       }
      //     },
      //     color: "#8193B2",
      //     fontSize: "12px",
      //   },
      //   axisLine: {
      //     lineStyle: {
      //       color: "#E4EDF8",
      //     },
      //   },
      //   nameTextStyle: {
      //     lineHeight: 80, //标题行高
      //     color: "#8193B2",
      //     verticalAlign: "top", //标题位置
      //     fontSize: "12px", // 设置最大宽度
      //     padding: [-28, 0, 0, 0], // 上右下左与原位置距离
      //   },
      // },
      //   tooltip: {
      //     trigger: "axis",
      //   },
      //   legend: {
      //     data: name,
      //     orient: "horizontal",
      //     align: "left",
      //     colorBy: "",
      //     x: "left", //可设定图例在左、右、居中
      //     y: "top", //可设定图例在上、下、居中
      //     icon: "circle",
      //     itemGap: 36,
      //     itemWidth: 8,
      //     itemHeight: 10,
      //     textStyle: {
      //       fontSize: "14px",
      //     },
      //     padding: [20, 0, 20, 0],
      //   },
      //   grid: {
      //     right: "50",
      //     bottom: "10",
      //     top: "100",
      //     left: "8",
      //     containLabel: true,
      //   },
      //   yAxis: {
      //     type: "value",
      //     min: 0,
      //     splitNumber: 5,
      //     // minInterval: 1,
      //     scale: true,
      //     name: "（薪酬 元）",
      //     axisLabel: {
      //       color: "#8193B2",
      //       fontSize: "12px",
      //     },
      //     nameTextStyle: {
      //       padding: [0, 40, 10, 0], // 上右下左与原位置距离
      //       color: "#8193B2",
      //     },
      //   },
      //   series: [],
      // };
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
          formatter: function (params) {
            let result = params[0].axisValue + "<br/>";
            // 创建一个固定顺序的数组
            const orderedNames = [
              "最高薪资",
              "中位数薪资",
              "平均薪资",
              "最低薪资",
            ];

            // 创建一个映射来存储所有值
            const valueMap = {};
            params.forEach((item) => {
              valueMap[item.seriesName] = item.value;
            });

            // 按固定顺序显示所有数据
            orderedNames.forEach((name) => {
              const value = valueMap[name] || 0;
              result += `<div style="display: flex; justify-content: space-between; align-items: center; margin: 4px 0;">
                <span style="color: #555;">${name}</span>
                <span style="color: #333; font-family: Arial; margin-left: 12px; font-size: 14px; font-weight: 500;">
                  ${Number(value).toLocaleString("zh-CN", {
                    minimumFractionDigits: 1,
                    maximumFractionDigits: 1,
                  })}
                </span>
              </div>`;
            });

            return result;
          },
          backgroundColor: "#fff",
          borderColor: "#e4edf8",
          borderWidth: 1,
          padding: [8, 12],
          textStyle: {
            color: "#333",
            fontSize: 13,
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: time,
          name: "(月份)",
          // boundaryGap: false,
          axisLabel: {
            formatter(val) {
              // 当字符串长度超过2时
              if (val.length > 2) {
                // 把字符串分割成字符串数组
                const array = val.split("");
                const index = array.indexOf("月");
                //在下标2处删除0个，加上回车
                array.splice(index + 1, 0, "\n\n");
                return array.join("");
              } else {
                return val;
              }
            },
            color: "#8193B2",
            fontSize: "12px",
          },
          axisLine: {
            lineStyle: {
              color: "#E4EDF8",
            },
          },
          nameTextStyle: {
            lineHeight: 80, //标题行高
            color: "#8193B2",
            verticalAlign: "top", //标题位置
            fontSize: "12px", // 设置最大宽度
            padding: [-28, 0, 0, -30], // 上右下左与原位置距离
          },
        },
        yAxis: [
          {
            type: "value",
          },
        ],
        series: [
          {
            name: "Email",
            type: "line",
            stack: "Total",
            areaStyle: {},
            emphasis: {
              focus: "series",
            },
            data: [120, 132, 101, 134, 90, 230, 210],
          },
          {
            name: "Union Ads",
            type: "line",
            stack: "Total",
            areaStyle: {},
            emphasis: {
              focus: "series",
            },
            data: [220, 182, 191, 234, 290, 330, 310],
          },
        ],
      };
      option.series = [];
      this.myChart.clear();
      option.series.push({
        name: "最高薪资",
        type: "line",
        smooth: true, // 设置为平滑曲线
        symbol: "circle",
        showSymbol: false,
        emphasis: {
          focus: "none",
          scale: true,
          itemStyle: {
            color: "#fff",
            borderColor: "#0B6EFF",
            borderWidth: 2,
          },
        },
        itemStyle: {
          borderWidth: 0, // 去掉圆点的边框
          color: "#4283FF",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 1,
                color: "rgba(88, 122, 250, 0.10)",
              },
              {
                offset: 0,
                color: "rgba(0, 78, 255, 0.50)",
              },
            ],
            global: false, // 缺省为 false
          },
        },
        data: this.chartData.city[0].maxSalary,
      });
      option.series.push({
        name: "最低薪资",
        type: "line",
        smooth: true, // 设置为平滑曲线
        symbol: "circle",
        showSymbol: false,
        emphasis: {
          focus: "none",
          scale: true,
          itemStyle: {
            color: "#fff",
            borderColor: "#0B6EFF",
            borderWidth: 2,
          },
        },
        itemStyle: {
          borderWidth: 0, // 去掉圆点的边框
          color: "rgba(88, 122, 250, 0.10)",
        },
        areaStyle: {
          color: "rgba(255, 255, 255, 1)", // 设置为白色，不透明
        },
        data: this.chartData.city[0].minSalary,
      });
      option.series.push({
        name: "中位数薪资",
        type: "line",
        smooth: true, // 设置为平滑曲线
        symbol: "none", // 去掉默认圆点
        itemStyle: {
          color: "rgba(0,0,0,0)", // 设置为完全透明
          borderWidth: 0, // 去掉圆点的边框
        },
        areaStyle: {
          color: "rgba(255, 255, 255, 0)", // 设置为白色，不透明
        },
        data: this.chartData.city[0].middleSalary,
      });
      option.series.push({
        name: "平均薪资",
        type: "line",
        smooth: true, // 设置为平滑曲线
        symbol: "none", // 去掉默认圆点
        itemStyle: {
          color: "rgba(0,0,0,0)", // 设置为完全透明
          borderWidth: 0, // 去掉圆点的边框
        },
        areaStyle: {
          color: "rgba(255, 255, 255, 0)", // 设置为白色，不透明
        },
        data: this.chartData.city[0].averageSalary,
      });

      // 对所有系列都应用相同的设置
      option.series.forEach((series) => {
        series.emphasis = {
          focus: "none",
          scale: true,
          itemStyle: {
            color: "#fff",
            borderColor: series.itemStyle?.color || "#0B6EFF",
            borderWidth: 2,
          },
        };
      });
      // 移除其他系列的图例显示
      option.series.forEach((series) => {
        series.showInLegend = false; // 在图例中隐藏该系列
      });
      option && this.myChart.setOption(option);
      window.addEventListener("resize", () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      // this.myChart.dispatchAction({
      //   type: "showTip",
      //   seriesIndex: 0,
      //   dataIndex: 1,
      // });
    },
    onRegionChange(val) {
      this.selectedRegionList = [];
      //console.log("onRegionChange", val);
      val.forEach((item) => {
        this.selectedRegionList.push(item.split("-")[0]);
      });
      if (this.isSetDeaultRegion) {
        this.isSetDeaultRegion = false;
        return;
      }
      this.fetchData();
    },
    handleDateChange(val) {
      // //console.log("触发获取！！！111", this.isSetDeaultTime);
      if (this.isSetDeaultTime) {
        this.isSetDeaultTime = false;
        return;
      }
      this.pickerMinDate = null;
      // //console.log("触发获取！！！222");

      this.fetchData();
    },
    averageCitySalary(values) {
      let salary = 0;
      values.forEach((item, index) => {
        salary = salary + item;
      });

      if (values.length > 0) {
        const result = salary / values.length;
        return result.toFixed(1);
      } else {
        return "保密";
      }
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem("userInfo")); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = "";
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: "85",
        layerName: "薪酬变化趋势",
        personId: localStorage.getItem("personId") || "",
        oaId: oaId,
      };
      console.log("----薪酬变化趋势---handleKnowClick--params", params);
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success("已成功提交");
        } else {
          this.$message.error(res.status_desc);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  width: 100%;
}

.chartMain {
  display: flex;
  align-items: center;
  padding-bottom: 15px;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
}
.regionLineChart {
  display: flex;
  align-items: center;
}
.regionLineDesc {
  display: flex;
  flex: 0.3;
  flex-wrap: wrap;
  // width: 400px;
  justify-content: left;
  align-content: center;
  margin: 10px;
}

.regionLineDescItem {
  margin: 10px 0px;
  width: 45%;
}
.descTitle {
  color: #555;
  font-size: 15px;
}
.descNum {
  display: flex;
  align-items: baseline;
  color: #1b78ff;
  font-size: 24px;
  font-weight: bold;
  margin-top: 22px;
  font-family: D-DIN-PRO-500-Medium;
}
.rmb {
  font-size: 18px;
}
.h100 {
  flex: 0.7;
  height: 20vw;
  width: 100%;

  min-width: 615px;
  min-height: 240px;
}
::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  line-height: 22px;

  display: flex;
  align-items: center;
  justify-content: center;
  height: 27px;
  min-width: 82px !important;
}
::v-deep .el-form-item {
  margin-bottom: 6px;
}
::v-deep .el-form-item:last-of-type {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
}
.search-container {
  display: flex;
  align-items: center;
}
</style>
